<template>
  <div class="edit-bg">
    <div class="edit-card">
      <button class="return-btn blue" type="button" @click="onCancel">返回</button>
      <div class="edit-title">{{ isEdit ? '编辑医疗服务项目' : '新增医疗服务项目' }}</div>
      <form @submit.prevent="onSubmit">
        <div class="edit-form-row">
          <label class="edit-label">财务分类：</label>
          <input v-model="formData.financialCategory" class="edit-input" placeholder="请输入财务分类" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">项目编码：</label>
          <input v-model="formData.projectCode" class="edit-input" required placeholder="请输入项目编码" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">国家编码：</label>
          <input v-model="formData.nationalCode" class="edit-input" placeholder="请输入国家编码" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">项目名称：</label>
          <input v-model="formData.projectName" class="edit-input" required placeholder="请输入项目名称" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">项目内涵：</label>
          <textarea v-model="formData.projectContent" class="edit-input description-textarea" placeholder="请输入项目内涵"></textarea>
        </div>
        <div class="edit-form-row">
          <label class="edit-label">除外内容：</label>
          <textarea v-model="formData.excludedContent" class="edit-input description-textarea" placeholder="请输入除外内容"></textarea>
        </div>
        <div class="edit-form-row">
          <label class="edit-label">计价单位：</label>
          <input v-model="formData.pricingUnit" class="edit-input" placeholder="请输入计价单位" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">价格：</label>
          <button type="button" class="price-btn" @click="decreasePrice">-</button>
          <input v-model.number="formData.price" class="edit-input price-input" 
                 style="width: 120px; text-align: center; margin: 0 8px;" 
                 placeholder="0.00" step="0.01" min="0" />
          <button type="button" class="price-btn" @click="increasePrice">+</button>
        </div>
        <div class="edit-form-row">
          <label class="edit-label">说明：</label>
          <textarea v-model="formData.description" class="edit-input remark-textarea" placeholder="请输入说明"></textarea>
        </div>
        <div class="edit-actions">
          <button class="edit-btn" type="submit" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getMedicalServiceItemById, addMedicalServiceItem, updateMedicalServiceItem } from '@/api/medicalServiceItems'

const router = useRouter()
const route = useRoute()
const loading = ref(false)

// 表单数据
const formData = reactive({
  itemId: null,
  financialCategory: '',
  projectCode: '',
  nationalCode: '',
  projectName: '',
  projectContent: '',
  excludedContent: '',
  pricingUnit: '',
  price: 0,
  description: ''
})

// 判断是否为编辑模式
const isEdit = computed(() => route.params.id && route.params.id !== 'new')

// 获取医疗服务项目详情
const fetchItemDetail = async (id) => {
  try {
    loading.value = true
    const response = await getMedicalServiceItemById(id)
    
    if (response.flag) {
      const item = response.data
      Object.assign(formData, {
        itemId: item.itemId,
        financialCategory: item.financialCategory || '',
        projectCode: item.projectCode || '',
        nationalCode: item.nationalCode || '',
        projectName: item.projectName || '',
        projectContent: item.projectContent || '',
        excludedContent: item.excludedContent || '',
        pricingUnit: item.pricingUnit || '',
        price: item.price || 0,
        description: item.description || ''
      })
    } else {
      ElMessage.error(response.message || '获取医疗服务项目详情失败')
      router.push('/medical-info/facilities')
    }
  } catch (error) {
    console.error('获取医疗服务项目详情失败:', error)
    ElMessage.error('获取医疗服务项目详情失败: ' + (error.message || '网络错误'))
    router.push('/medical-info/facilities')
  } finally {
    loading.value = false
  }
}

// 价格调整
const increasePrice = () => {
  formData.price = Number((Number(formData.price) + 0.1).toFixed(2))
}

const decreasePrice = () => {
  formData.price = Math.max(0, Number((Number(formData.price) - 0.1).toFixed(2)))
}

// 表单提交
const onSubmit = async () => {
  // 表单验证
  if (!formData.projectCode.trim()) {
    ElMessage.warning('请输入项目编码')
    return
  }
  if (!formData.projectName.trim()) {
    ElMessage.warning('请输入项目名称')
    return
  }

  try {
    loading.value = true
    
    const submitData = {
      ...formData,
      financialCategory: formData.financialCategory?.trim() || '',
      projectCode: formData.projectCode.trim(),
      nationalCode: formData.nationalCode?.trim() || '',
      projectName: formData.projectName.trim(),
      projectContent: formData.projectContent?.trim() || '',
      excludedContent: formData.excludedContent?.trim() || '',
      pricingUnit: formData.pricingUnit?.trim() || '',
      description: formData.description?.trim() || ''
    }

    let response
    if (isEdit.value) {
      // 编辑模式
      response = await updateMedicalServiceItem(submitData)
    } else {
      // 新增模式
      delete submitData.itemId // 新增时不需要ID
      response = await addMedicalServiceItem(submitData)
    }

    if (response.flag) {
      ElMessage.success(response.message || (isEdit.value ? '修改成功' : '新增成功'))
      router.push('/medical-info/facilities')
    } else {
      ElMessage.error(response.message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error) {
    console.error('保存医疗服务项目失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 取消操作
const onCancel = () => {
  router.push('/medical-info/facilities')
}

// 页面初始化
onMounted(() => {
  if (isEdit.value) {
    // 编辑模式：从API获取数据
    fetchItemDetail(route.params.id)
  } else {
    // 新增模式：尝试从localStorage获取数据（如果有的话）
    const storedData = localStorage.getItem('editMedicalServiceItem')
    if (storedData) {
      try {
        const parsedData = JSON.parse(storedData)
        Object.assign(formData, {
          financialCategory: parsedData.financialCategory || '',
          projectCode: parsedData.projectCode || '',
          nationalCode: parsedData.nationalCode || '',
          projectName: parsedData.projectName || '',
          projectContent: parsedData.projectContent || '',
          excludedContent: parsedData.excludedContent || '',
          pricingUnit: parsedData.pricingUnit || '',
          price: parsedData.price || 0,
          description: parsedData.description || ''
        })
        localStorage.removeItem('editMedicalServiceItem')
      } catch (error) {
        console.warn('解析存储的医疗服务项目数据失败:', error)
      }
    }
  }
})
</script>

<style scoped>
.edit-bg {
  min-height: 100vh;
  background: #f5f6fa;
  width: 100%;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
  padding: 0;
}
.edit-card {
  background: #fff;
  border-radius: 0;
  box-shadow: none;
  padding: 0;
  width: 100%;
  min-width: 0;
  max-width: none;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
}
.edit-title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  margin: 32px 0 32px 64px;
  text-align: left;
  letter-spacing: 1px;
}
.edit-form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 18px;
  padding: 0;
}
.edit-label {
  width: 160px;
  color: #34495e;
  font-size: 16px;
  text-align: right;
  margin-right: 12px;
  position: relative;
  margin-top: 8px;
}
.edit-input {
  flex: 1;
  min-height: 36px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 15px;
  width: 100%;
  line-height: 1.4;
}
.edit-input:not(.price-input) {
  max-width: 600px;
}
.description-textarea {
  min-height: 80px;
  height: 80px;
  resize: vertical;
  font-family: inherit;
}
.edit-actions {
  margin: 32px 0 0 64px;
  display: flex;
  gap: 18px;
}
.edit-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 32px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.return-btn {
  position: absolute;
  top: 24px;
  right: 32px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 32px;
  font-size: 16px;
  cursor: pointer;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}
.return-btn.blue {
  background: #409eff;
  color: #fff;
}
.price-input {
  width: 100px !important;
  min-width: 60px;
  max-width: 120px;
  display: inline-block;
}
.price-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #d0d5dd;
  background: #f5f6fa;
  color: #34495e;
  border-radius: 4px;
  font-size: 20px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0 2px;
  transition: background 0.2s;
}
.price-btn:hover {
  background: #eaf3ff;
}
.remark-textarea {
  min-height: 108px;
  height: 108px;
  resize: vertical;
  font-family: inherit;
}
</style>